package com.example.fanyi.api

import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.http.POST
import retrofit2.http.Query
import retrofit2.http.FormUrlEncoded
import retrofit2.http.Field
import java.util.concurrent.TimeUnit

interface YoudaoApi {
    @FormUrlEncoded
    @POST("api")
    suspend fun translate(
        @Field("q") text: String,
        @Field("from") from: String,
        @Field("to") to: String,
        @Field("appKey") appKey: String = "61358e19277bfc8f",
        @Field("salt") salt: String,
        @Field("sign") sign: String,
        @Field("signType") signType: String = "v3",
        @Field("curtime") curtime: String
    ): YoudaoResponse

    companion object {
        private const val BASE_URL = "https://openapi.youdao.com/"

        fun create(): YoudaoApi {
            val logger = HttpLoggingInterceptor().apply { 
                level = HttpLoggingInterceptor.Level.BODY 
            }

            val client = OkHttpClient.Builder()
                .addInterceptor(logger)
                .connectTimeout(15, TimeUnit.SECONDS)
                .readTimeout(15, TimeUnit.SECONDS)
                .writeTimeout(15, TimeUnit.SECONDS)
                .build()

            return Retrofit.Builder()
                .baseUrl(BASE_URL)
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .build()
                .create(YoudaoApi::class.java)
        }
    }
}

data class YoudaoResponse(
    val errorCode: String,
    val query: String? = null,
    val translation: List<String> = emptyList(),
    val basic: Basic? = null,
    val web: List<WebResult>? = null,
    val l: String? = null,
    val dict: Dict? = null,
    val webdict: WebDict? = null,
    val tSpeakUrl: String? = null,
    val speakUrl: String? = null,
    val returnPhrase: List<String>? = null
)

data class Basic(
    val phonetic: String? = null,
    val explains: List<String>? = null
)

data class WebResult(
    val key: String,
    val value: List<String>
)

data class Dict(
    val url: String
)

data class WebDict(
    val url: String
) 